package com.zhiqianbao.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.zhiqianbao.R;
import com.zhiqianbao.utils.Constants;

import java.security.PrivateKey;
import java.security.cert.X509Certificate;
import cn.trinea.android.common.util.StringUtils;

/**
 * Created by liang on 2016/1/8.
 */
public class DialogContractActivity extends BaseActivity {
    WebView mWebView;
    TextView textviewRegisterTitle;
    RelativeLayout titleLayout;

    String url;
    String title;
    public static X509Certificate[] mX509Certificates;

    public static PrivateKey mPrivateKey;

    public static String CERTFILE_PASSWORD;
    String encoding;
    String method;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_contract);


        Intent intent = getIntent();

        url = (String) intent.getSerializableExtra("url");
        title = (String) intent.getSerializableExtra("title");
        method = (String) intent.getSerializableExtra("method");
        encoding = (String) intent.getSerializableExtra("encoding");
        if(StringUtils.isBlank(method)){
            method = "GET";
        }
        if(StringUtils.isBlank(encoding)){
            encoding = "UTF-8";
        }
        init();
        initView();
    }




    private void initView() {
         mWebView=(WebView)findViewById(R.id.mWebView);
         textviewRegisterTitle=(TextView)findViewById(R.id.textview_register_title);
         titleLayout=(RelativeLayout)findViewById(R.id.relativeLayout_dialog_cantract_title);

        WebSettings webSettings = mWebView.getSettings();
        //设置WebView属性，能够执行Javascript脚本
        webSettings.setJavaScriptEnabled(true);
        //设置可以访问文件
        webSettings.setAllowFileAccess(false);
        webSettings.setLoadWithOverviewMode(true);
        //设置支持缩放
        webSettings.setBuiltInZoomControls(false);
        webSettings.setSupportZoom(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setDatabaseEnabled(true);
        webSettings.setAppCacheEnabled(true);

        // android 5.0以上默认不支持Mixed Content
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webSettings.setMixedContentMode(
                    WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE);
        }


//        mWebView.setWebChromeClient(new WebChromeClient(){
//
//            @Override
//            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
//                // super.onReceivedSslError(view, handler, error);
//                handler.proceed();// 接受所有证书
//            }
//
//        });



        mWebView.setWebViewClient(new WebViewClient() {


            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
               // super.onReceivedSslError(view, handler, error);
//                super.onReceivedSslError(view, handler, error);
                handler.proceed();// 接受所有证书



            }



        });



        WebViewClient onReceivedClientCertRequest;
        mWebView.getSettings().setJavaScriptEnabled(true);

        //设置字体编码
        webSettings.setDefaultTextEncodingName(encoding);

        //加载需要显示的网页
        if(!url.startsWith("http:") && !url.startsWith("https:")){
            url = Constants.API_ROOT + url;
        }

        if("POST".equalsIgnoreCase(method)){
            String uri = url.contains("?") ? url.substring(0,url.indexOf("?")) : url;
            String paramStr = url.contains("?") ? url.substring(url.indexOf("?") + 1) : "";
            try{
                paramStr = paramStr.replaceAll("\\+","%2B");
            }catch (Exception e){
                e.printStackTrace();
            }
            mWebView.postUrl(uri, paramStr.getBytes());
        }else{
            Log.i(getClass().getSimpleName(), "url===" + url);
            mWebView.loadUrl(url);
        }
        //覆盖WebView默认使用第三方或系统默认浏览器打开网页的行为，使网页用WebView打开
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                //返回值是true的时候控制去WebView打开，为false调用系统浏览器或第三方浏览器
                Log.i("WebViewClient", "url:" + url);
                view.loadUrl(url);
                return true;
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                Log.i("WebViewClient", "onPageStarted--url:" + url);
                super.onPageStarted(view, url, favicon);
            }


            @Override
            public void onPageFinished(WebView view, String url) {
                Log.i("WebViewClient", "onPageFinished--url:" + url);
                super.onPageFinished(view, url);

            }

        });
        mWebView.setWebChromeClient(new MyWebChromeClient());// 设置浏览器可弹窗
        textviewRegisterTitle.setText(title);

        if (StringUtils.isBlank(title)){
            titleLayout.setVisibility(View.GONE);
        }

        mWebView.addJavascriptInterface(this, "webview");
    }

    /**
     * 浏览器可弹窗
     *
     * @author Administrator
     *
     */
    final class MyWebChromeClient extends WebChromeClient {
        @Override
        public boolean onJsConfirm(WebView view, String url, String message,
                                   final JsResult result) {
            showShortToast1(message);
            return true;
        }
    }

    @JavascriptInterface
    public void cancel() {
        this.finish();
    }
}
